package org.chengn.level_hard.context2276;

import java.util.Map;
import java.util.TreeMap;

/**
 * @Title: Context2276
 * @Author ChengN
 * @Package org.chengn.level_hard.context2276
 * @Date 2023/12/16 22:43
 * @description: 统计区间中的整数数目
 */
public class Context2276 {
    TreeMap<Integer, Integer> treeMap = new TreeMap<>();
    int cnt = 0;

    public Context2276() {

    }

    public void add(int left, int right) {
        Map.Entry<Integer, Integer> integerIntegerEntry = treeMap.floorEntry(right);
        while (integerIntegerEntry != null && integerIntegerEntry.getValue() >= left) {
            int l = integerIntegerEntry.getKey(), r = integerIntegerEntry.getValue();
            left = Math.min(l ,left);
            right = Math.max(r, right);
            cnt -= (r - l + 1);
            treeMap.remove(l);
            integerIntegerEntry = treeMap.floorEntry(right);
        }

        cnt += right - left + 1;
        treeMap.put(left, right);
    }

    public int count() {
        return cnt;
    }
}
